import Vue from 'vue'
import axios from 'axios';
import moment from "moment"
import ElementUI from 'element-ui'; 
import {
    Message
} from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.prototype.ipc = ipc
// Vue.prototype.$path = window.require("path");
// 服务器的域名/ip
// axios.defaults.withCredentials=true;//让ajax携带cookie
let ip = "http://127.0.0.1:3000/" 
ip = "https://w3cjs.cn/"
const instances = axios.create({
    baseURL: ip,
    timeout: 30000, // 请求超时时间，1分钟
    headers: {
        'content-type': 'application/x-www-form-urlencoded'
    }
});
// request请求拦截器

instances.interceptors.request.use(
    config => {
        // Loading.service({text: '加载中...'})   这是全局的loading
        config.headers = {
        }
        return config
    },
    error => {
        Promise.reject(error)
    }
)

// respone响应拦截器
instances.interceptors.response.use(
    response => {
        // Loading.service().close()  响应成功，关闭全局的loading
        return response
    },
    error => {
        // Loading.service().close()  响应错误，关闭全局的loading
        // Message({
        //     message: '服务器繁忙，请稍后重试',
        //     type: 'error', 
        //     duration: 4 * 1000
        // })
        return Promise.reject(error)
    }
)
Vue.prototype.post = (url, data) => {
    return new Promise((resolve, reject) => {
        instances.post(url, data).then(res => {
            resolve(res.data)
        }).catch(err => {
            resolve({ code: 1, msg: err })
        })
    })
}
Vue.prototype.postfile = (url, params) => {
    const config = {
        headers: { "Content-Type": "multipart/form-data;boundary=" + new Date().getTime() }
    };
    return new Promise((resolve, reject) => {
        instances.post(url, params, config)
            .then(async (res) => {
                resolve(res)
            })
            .catch(error => {
                reject(error)
            })
    })
}
Vue.prototype.base64ToBlob = (urlData, type) => {
    let arr = urlData.split(",");
    let mime = arr[0].match(/:(.*?);/)[1] || type;
    // 去掉url的头，并转化为byte
    let bytes = window.atob(arr[1]);
    // 处理异常,将ascii码小于0的转换为大于0
    let ab = new ArrayBuffer(bytes.length);
    // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
    let ia = new Uint8Array(ab);
    for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], {
        type: mime,
    });
}
// Vue.prototype.ips = process.env.NODE_ENV == "development" ? "ws://127.0.0.1:3000/call?name=" : "wss://w3cjs.cn/call?name="
Vue.prototype.ips = process.env.NODE_ENV == "development" ? "wss://w3cjs.cn/call?name=" : "wss://w3cjs.cn/call?name="
Vue.prototype.AllTime = (val) => {
    //设置年月日时分秒
    if (!val) return "";
    var date = new Date(Number(val));
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var h = date.getHours();
    h = h < 10 ? "0" + h : h;
    var f = date.getMinutes();
    f = f < 10 ? "0" + f : f;
    var s = date.getSeconds();
    s = s < 10 ? "0" + s : s;
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    return year + "-" + month + "-" + strDate + " " + h + ":" + f + ":" + s;
}
Vue.config.productionTip = false;
Vue.use(ElementUI);
ipc.on("message", (e, res) => {
    window.dispatchEvent(new CustomEvent('message', {
        detail: res
    }))
})
ipc.on("YC", (e, res) => {
    window.dispatchEvent(new CustomEvent('YC', {
        detail: res
    }))
})

Vue.prototype.setBase = (text) => {
    let ciphertext = CryptoJS.AES.encrypt(text, 'lt007').toString()
    return ciphertext
}
Vue.prototype.getBase = (text) => {
    let bytes = CryptoJS.AES.decrypt(text, 'lt007')
    return bytes.toString(CryptoJS.enc.Utf8);
}
let urlParam = (name) => {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.href
        .substr(window.location.href.indexOf("?") + 1)
        .match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]);
    return ""; //返回参数值
}
Vue.prototype.urlParam = urlParam
Vue.prototype.ok = (e, time) => {
    Message({
        message: "" + e,
        type: "success",
        duration: time ? time : 1500,
        offset: 30
    });
}
Vue.prototype.err = (e, time) => {
    Message({
        message: "" + e,
        type: "warning",
        duration: time ? time : 1500,
        offset: 30
    });
}
Vue.prototype.$moment = moment
let Socket = ''
let setIntervalWesocketPush = null
let createSocket = async e => {
    if (e) {
        ipc.invoke("sdg", {
            key: localStorage.getItem("uuid") + "wsurl",
            type: "set",
            value: e,
        });

    } else {
        let obj = await ipc.invoke("sdg", {
            key: localStorage.getItem("uuid") + "wsurl",
            type: "get",
            value: e,
        });
        if (obj) {
            e = obj
        }
    }
    ipc.send("message", { type: "ydOut" })//
    ipc.send("message", { type: "gvOut" })//
    Socket && Socket.close()
    if (!Socket) {
        console.log('建立websocket连接')
        Socket = new WebSocket(e)
        Socket.onopen = onopen
        Socket.onmessage = onmessage
        Socket.onerror = onerror
        Socket.onclose = onclose
    } else {
        console.log('websocket已连接')
    }
}
Vue.prototype.createSocket = createSocket
/**打开WS之后发送心跳 */
const onopen = () => {
    sendPing()
}

/**连接失败重连 */
const onerror = () => {
    console.log('连接失败重连中')
    Socket.close()
    clearInterval(setIntervalWesocketPush)

    if (Socket.readyState !== 3) {
        Socket = null
        createSocket()
    }
}

/**WS数据接收统一处理 */
const onmessage = evt => {
    window.dispatchEvent(new CustomEvent('wsOnmessage', {
        detail: {
            data: JSON.parse(evt.data || "{}")
        }
    }))
    // var blob = new Blob([evt.data]);
    // //将 Blob对象 读成字符串
    // var reader = new FileReader();
    // reader.readAsText(evt.data, 'utf-8');
    // reader.onload = (e) => {
    //     window.dispatchEvent(new CustomEvent('wsOnmessage', {
    //         detail: {
    //             data: reader.result
    //         }
    //     }))
    // }

}

/**
 * 发送数据但连接未建立时进行处理等待重发
 * @param {any} message 需要发送的数据
 */
const connecting = message => {
    setTimeout(() => {
        if (Socket.readyState === 0) {
            connecting(message)
        } else {
            Socket.send(JSON.stringify(message))
        }
    }, 1000)
}

/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
Vue.prototype.sendWSPush = message => {
    if (Socket !== null && Socket.readyState === 3) {
        Socket.close()
        createSocket()
    } else if (Socket.readyState === 1) {
        Socket.send(JSON.stringify(message))
    } else if (Socket.readyState === 0) {
        connecting(message)
    }
}

/**断开重连 */
const onclose = () => {
    clearInterval(setIntervalWesocketPush)
    console.log('websocket已断开....正在尝试重连')
    if (Socket.readyState !== 2) {
        Socket = null
        createSocket()
    }
}
/**发送心跳
 * @param {number} time 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
let sendPing = async (time = 5000, ping = 'ping') => {
    let uder = await ipc.invoke("sdg", {
        key: localStorage.getItem("uuid") + "userObj",
        type: "get"
    });
    if (uder) {
        let obj = JSON.stringify({
            type: "login",
            name: JSON.parse(uder).uuid,
        })
        // clearInterval(setIntervalWesocketPush)
        // Socket.send(obj)
        // setIntervalWesocketPush = setInterval(() => {
        Socket.send(obj)
        // }, time)
    }
}
Vue.prototype.sendPing = sendPing